package com.javajavadog.ui.base;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.javajavadog.ui.R;

import java.util.List;
import java.util.Map;

/**
 * Highly customized activity shows a list.
 */
public abstract class BaseListActivity extends FragmentHostActivity {

    @Override
    public Fragment getContentFragment() {
        return BaseListFragment.newInstance();
    }

    public static class BaseListFragment extends Fragment {
        public int mListViewId;

        public static BaseListFragment newInstance() {
            BaseListFragment f = new BaseListFragment();
            return f;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            mListViewId = View.generateViewId();
            ListView lv = new ListView(getActivity());
            addFooter(lv);
            lv.setId(mListViewId);
            return lv;
        }

        private void addFooter(ListView lv) {
            lv.setFooterDividersEnabled(false);
            View space = LayoutInflater.from(getActivity()).inflate(R.layout.space, lv, false);
            lv.addFooterView(space, null, false);
        }

        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            ListView lv = (ListView) view.findViewById(mListViewId);
            lv.setAdapter(createListData());
            BaseListActivity a = (BaseListActivity) getActivity();
            lv.setOnItemClickListener(a.getOnItemClickListener());
        }

        private ListAdapter createListData() {
            BaseListActivity a = (BaseListActivity) getActivity();
            List<Map<String, String>> data = a.getListData();

            ListAdapter adapter = new SimpleAdapter(getActivity(), data,
                    R.layout.list_item_simple, new String[]{"item_name", "item_subtitle"},
                    new int[]{R.id.text_view_list_item, R.id.text_view_list_item_subtitle});

            return adapter;
        }
    }

    public abstract AdapterView.OnItemClickListener getOnItemClickListener();

    public abstract List<Map<String, String>> getListData();
}
